using System;
using System.IO;
using System.Text.Json;

namespace Common.Untils
{
    public class VersionInfo
    {
        public string Version { get; set; }
        public DateTime LastUpdateTime { get; set; }

        private static readonly string VersionFilePath = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
            "SanmaoTools",
            "version.json"
        );

        public static VersionInfo Load()
        {
            try
            {
                if (File.Exists(VersionFilePath))
                {
                    var json = File.ReadAllText(VersionFilePath);
                    return JsonSerializer.Deserialize<VersionInfo>(json);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载版本信息失败: {ex.Message}");
            }

            return new VersionInfo { Version = "1.0.0", LastUpdateTime = DateTime.Now };
        }

        public static void Save(string version)
        {
            try
            {
                var versionInfo = new VersionInfo
                {
                    Version = version,
                    LastUpdateTime = DateTime.Now
                };

                var directory = Path.GetDirectoryName(VersionFilePath);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                var json = JsonSerializer.Serialize(versionInfo, new JsonSerializerOptions
                {
                    WriteIndented = true
                });

                File.WriteAllText(VersionFilePath, json);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"保存版本信息失败: {ex.Message}");
            }
        }
    }
}